<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<link rel="stylesheet" href="style/style.css">
</head>
<body>
	
	<!-- 左侧放大镜容器 -->
	<div class="small"> 
		<!-- 贴膜:防止正方形小盒子在随鼠标移动时产生的抽搐 -->
		<div class="wrap"></div>
		<!-- 左侧放大镜图片 -->
		<img src="images/timg.jpg" alt="">
		<!-- 小盒子 -->
		<span class="grayBox"></span>
	</div>
	<!-- 大图容器 -->
	<div class="big">
		<!-- 大图图片 -->
		<img src="images/timg.jpg" alt="">
	</div>

</body>
<script>
	function Amplification(){
		// 小盒子容器
		this.small = document.querySelector('.small');
		// 正方形小盒子
		this.square = document.querySelector(".grayBox");
		// 大盒子容器
		this.big = document.querySelector('.big');
		// 获取放大的图片
		this.big_img = document.querySelector('.big img');
		// 获取width和height的样式(防止因offset产生的性能消耗)
		// square的宽高
		this.square_size = {
			width : parseInt(getComputedStyle(this.square).width),
			height : parseInt(getComputedStyle(this.square).height)
		}
		// small的宽高
		this.small_size = {
			width : this.small.offsetWidth,
			height : this.small.offsetHeight
		}
		// big的宽高
		this.big_size = {
			width : parseInt(getComputedStyle(this.big).width),
			height : parseInt(getComputedStyle(this.big).height)
		}
		// 获取放大的图片的宽高
		this.big_img_size = {
			width  : parseInt(getComputedStyle(this.big_img).width),
			height : parseInt(getComputedStyle(this.big_img).height)
		}
		// 调用事件
		this.bindEvent();
	}
	Amplification.prototype.bindEvent = function(){
		var self = this;
		// 元素的隐藏和显示
		this.small.onmouseover = function(){
			self.square.style.display = "block";
			self.big.style.display = "block";
		}
		this.small.onmouseout = function(){
			self.square.style.display = "none";
			self.big.style.display = "none";
		}
		// 鼠标运动
		this.small.onmousemove = function(evt){
			var e = evt || event;
			// 边界处理
			// 计算small - square的剩余的移动距离
			var _left = e.offsetX - self.square_size.width / 2;
			var _top = e.offsetY - self.square_size.height / 2;
			// 判断X轴方向的极值
			if(_left < 0){ //极小值
				_left = 0;
			}
			var max_left = self.small_size.width - self.square_size.width - 8; //8为边框长度
			if(_left > max_left){ //极大值
				_left = max_left;
			}
			// 判断Y轴方向的极值
			if(_top < 0){ //极小值
				_top = 0;
			}
			var max_top = self.small_size.height - self.square_size.height - 8; //8为边框长度
			if(_top > max_top){ //极大值
				_top = max_top;
			}
			self.square.style.left = _left + 'px';
			self.square.style.top = _top + 'px';
			// 计算位移的百分比
			var prop_left = (_left / max_left).toFixed(2);
			var prop_top = (_top / max_top).toFixed(2);
			// 计算大盒子的最大移动距离
			var big_box_max_left = self.big_img_size.width - self.big_size.width;
			var big_box_max_top  = self.big_img_size.height - self.big_size.height;
			// 计算距离
			self.big_img.style.left = - big_box_max_left * prop_left + 'px';
			self.big_img.style.top = - big_box_max_top * prop_top + 'px';
		}
	}
	var af = new Amplification();
</script>
</html>